<template>
  <view class="content">
    <!-- 上传组件 -->
    <upload-demo type="file" :list="fileList" @success="handleUploadSuccess"></upload-demo>

    <!-- 文件状态展示 -->
    <view v-if="copyStatus" class="status">
      <text class="title">文件状态：</text>
      <text class="message">{{ copyStatus }}</text>
    </view>

    <!-- 提示上传文件 -->
    <view v-if="!filePath && !copyStatus" class="status">
      <text class="message">请先上传文件以加载内容。</text>
    </view>

    <!-- 数据库内容展示 -->
    <view v-if="dbContent.length > 0" class="db-content">
      <text class="title">数据库内容：</text>

      <!-- 使用 uni-ui 表格组件 -->
      <uni-card>
        <uni-table border stripe>
          <!-- 表头 -->
          <uni-tr>
            <uni-th v-for="(column, index) in columns" :key="index">{{ column }}</uni-th>
          </uni-tr>

          <!-- 表格内容 -->
          <uni-tr v-for="(row, rowIndex) in dbContent" :key="rowIndex">
            <uni-td v-for="(value, key) in row" :key="key">{{ value }}</uni-td>
          </uni-tr>
        </uni-table>

        <!-- 分页控制 -->
        <view class="pagination">
          <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
          <text>第 {{ currentPage }} 页</text>
          <button @click="nextPage" :disabled="dbContent.length < itemsPerPage">下一页</button>
        </view>
      </uni-card>
    </view>
  </view>
</template>

<script>
import UploadDemo from '@/components/UploadDemo.vue';
import { copyFileToAppDir } from '@/utils/copyexcel';

export default {
  components: {
    UploadDemo,
  },
  data() {
    return {
      fileList: [],
      filePath: '',
      copyStatus: '',
      dbName: 'uploadedDB',
      dbContent: [],
      columns: [],
      isDatabaseOpen: false,
      currentPage: 1,
      itemsPerPage: 10,
    };
  },
  methods: {
    async handleUploadSuccess(file) {
      this.copyStatus = '正在复制文件...';
      try {
        const copiedFilePath = await copyFileToAppDir(file.tempFilePath);
        plus.storage.setItem('lastFilePath', copiedFilePath);
        this.filePath = copiedFilePath;
        this.copyStatus = `文件复制成功: ${copiedFilePath}`;
        await this.openAndReadDatabase(copiedFilePath);
      } catch (error) {
        this.copyStatus = `文件复制失败: ${error.message}`;
        console.error('[错误] 文件复制失败:', error);
      }
    },

    async openAndReadDatabase(dbPath) {
      try {
        this.copyStatus = '正在加载数据库...';
        await this.ensureDatabaseClosed(); // 确保关闭旧连接
        await this.openDatabase(dbPath);
        
        const tableName = await this.getFirstTableName();
        await this.loadTableContent(tableName, this.currentPage);
        this.copyStatus = '数据库加载成功';
      } catch (error) {
        this.copyStatus = `数据库加载失败: ${error.message}`;
        console.error('[错误] 数据库加载失败:', error);
      }
    },

    // 新增数据库关闭方法
    ensureDatabaseClosed() {
      return new Promise((resolve) => {
        plus.sqlite.closeDatabase({
          name: this.dbName,
          success: () => {
            console.log(`✅ 数据库 ${this.dbName} 已关闭`);
            this.isDatabaseOpen = false;
            resolve();
          },
          fail: (e) => {
            console.warn('⚠️ 关闭数据库失败（可能未打开）:', e);
            resolve(); // 即使关闭失败也继续执行
          }
        });
      });
    },

    openDatabase(dbPath) {
      return new Promise((resolve, reject) => {
        plus.sqlite.openDatabase({
          name: this.dbName,
          path: dbPath,
          success: () => {
            console.log(`✅ 数据库 ${this.dbName} 打开成功`);
            this.isDatabaseOpen = true;
            resolve();
          },
          fail: (e) => {
            console.error('[错误] 数据库打开失败:', e);
            reject(new Error('数据库打开失败'));
          },
        });
      });
    },

    getFirstTableName() {
      return new Promise((resolve, reject) => {
        const sql = "SELECT name FROM sqlite_master WHERE type='table' LIMIT 1";
        plus.sqlite.selectSql({
          name: this.dbName,
          sql,
          success: (results) => {
            if (results.length === 0) reject(new Error('未找到任何表'));
            resolve(results[0].name);
          },
          fail: (e) => {
            console.error('[错误] 获取表名失败:', e);
            reject(new Error('获取表名失败'));
          },
        });
      });
    },

    loadTableContent(tableName, page) {
      return new Promise((resolve, reject) => {
        const offset = (page - 1) * this.itemsPerPage;
        const sql = `SELECT * FROM ${tableName} ORDER BY rowid LIMIT ${this.itemsPerPage} OFFSET ${offset}`;
        
        plus.sqlite.selectSql({
          name: this.dbName,
          sql,
          success: (results) => {
            this.dbContent = results;
            this.columns = results[0] ? Object.keys(results[0]) : [];
            resolve();
          },
          fail: (e) => {
            console.error('[错误] 加载表数据失败:', e);
            reject(new Error('加载表数据失败'));
          },
        });
      });
    },

    async nextPage() {
      this.currentPage++;
      const tableName = await this.getFirstTableName();
      await this.loadTableContent(tableName, this.currentPage);
    },

    async prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        const tableName = await this.getFirstTableName();
        await this.loadTableContent(tableName, this.currentPage);
      }
    },
  },
  async mounted() {
    const lastFilePath = plus.storage.getItem('lastFilePath');
    if (lastFilePath) {
      this.filePath = lastFilePath;
      await this.openAndReadDatabase(lastFilePath);
    }
  },
  // 新增页面卸载逻辑
  beforeDestroy() {
    if (this.isDatabaseOpen) {
      plus.sqlite.closeDatabase({
        name: this.dbName,
        success: () => {
          console.log(`✅ 数据库 ${this.dbName} 已关闭`);
          this.isDatabaseOpen = false;
        },
        fail: (e) => {
          console.warn('⚠️ 页面卸载时关闭数据库失败:', e);
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.content {
  

  .status {
    margin-top: 40rpx;
    padding: 20rpx;
    background-color: #f0f0f0;
    border-radius: 16rpx;

    .title {
      font-size: 28rpx;
      font-weight: bold;
    }

    .message {
      margin-left: 20rpx;
      font-size: 26rpx;
      color: #333;
    }
  }

  .db-content {
    margin-top: 40rpx;
    width: 100%; // 确保 db-content 宽度为100%
    box-sizing: border-box; // 包含padding和border在内计算宽度

    .title {
      font-size: 28rpx;
      font-weight: bold;
      margin-bottom: 20rpx;
      display: block;
    }

    uni-card {
      width: 100%; // 确保 card 宽度为100%
    }

    .pagination {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 30rpx;
      gap: 20rpx;

      button {
        padding: 8rpx 24rpx;
        font-size: 26rpx;
        background-color: #007AFF;
        color: white;
        border-radius: 8rpx;

        &:disabled {
          background-color: #aaa;
        }
      }

      text {
        font-size: 26rpx;
      }
    }
  }
}
</style>